package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.service.SendSmsService;
import com.ruoyi.system.tools.BooleanMessage;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SendSmsServiceImpl implements SendSmsService {

//    @Autowired
//    private RedisTemplate redisTemplate;

    @Override
    public boolean send(String phoneNum, String ppPassword) {

        /**
         * regionID @cn-hangzhou
         * 阿里云短信服务账号 @accessKeyId
         * 阿里云短信服务密码 @secret
         * */
        // 链接阿里云  这个不需要动 cn-hangzhou  accessKeyId : 账号  secret: 密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", RuoYiConfig.getAliyunkeyid(), RuoYiConfig.getAliyunkeysecret());
        IAcsClient client = new DefaultAcsClient(profile);
        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//官方说不要动
        request.setVersion("2017-05-25");//官方说不要动
        request.setAction("SendSms");//事件名称

        // 自定义的参数 （手机号,验证码,签名,模板!)
        request.putQueryParameter("PhoneNumbers",phoneNum);//手机号
        request.putQueryParameter("SignName","人社部专家中心");//签名
        request.putQueryParameter("TemplateCode","SMS_269045510");//模板CODE
        request.putQueryParameter("TemplateParam","{'password':'"+ppPassword+"'}");    // 新的密码


        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();//成功
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 自定义 循环调用
    @Override
    public boolean sendZDY(String phoneNum, String mubanid,Map<String,Object> ppMap) {

        /**
         * regionID @cn-hangzhou
         * 阿里云短信服务账号 @accessKeyId
         * 阿里云短信服务密码 @secret
         * */
        // 链接阿里云  这个不需要动 cn-hangzhou  accessKeyId : 账号  secret: 密码
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", RuoYiConfig.getAliyunkeyid(), RuoYiConfig.getAliyunkeysecret());
        IAcsClient client = new DefaultAcsClient(profile);
        // 构建请求
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");//官方说不要动
        request.setVersion("2017-05-25");//官方说不要动
        request.setAction("SendSms");//事件名称

        // 自定义的参数 （手机号,验证码,签名,模板!)
        request.putQueryParameter("PhoneNumbers",phoneNum);//手机号
        request.putQueryParameter("SignName","人社部专家中心");//签名
        request.putQueryParameter("TemplateCode",mubanid);//模板CODE
        request.putQueryParameter("TemplateParam",JSONObject.toJSONString(ppMap));    // 替换标签


        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();//成功
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    public BooleanMessage send短信Post(String pp号码, String pp内容) {
        HttpURLConnection conn = null;
        StringBuilder buf = new StringBuilder();
        OutputStream os = null;
        InputStream is = null;
        PrintWriter pw = null;
        BufferedReader br = null;
        OutputStreamWriter ow = null;
        try {
            String encode = URLEncoder.encode(pp内容,"utf-8");
            encode =URLEncoder.encode(encode,"utf-8");
            URL connectUrl;


            connectUrl = new URL("http://dx.12333.gov.cn/sms/send/smsSend.action");
            conn = (HttpURLConnection) connectUrl.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            int mm时间戳分 = (int)(System.currentTimeMillis() / 1000 / 60);
            conn.setConnectTimeout(mm时间戳分);
            conn.setReadTimeout(mm时间戳分);
            conn.connect();
            os = conn.getOutputStream();
            ow = new OutputStreamWriter(os, "utf-8");
            pw = new PrintWriter(ow, true);
            String mmUUID = UUID.randomUUID().toString();
            pw.println( "uuid="+mmUUID+"&timeOut="+mm时间戳分+"&phone="+pp号码+"&isLong=1&content="+encode+"&appName=btrrbsxt&smsKey=Btbs@530&businessName=m1");
            pw.flush();
            is = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(is, "utf-8"));
            String line = null;
            while ((line = br.readLine()) != null) {
                buf.append(line);
            }


        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Exception e) {
                }
            }
            if(ow!=null) {
                try {
                    ow.close();
                } catch (IOException e) {
                }
            }
            if (pw != null) {
                try {
                    pw.close();
                } catch (Exception e) {
                }
            }
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
            if (conn != null) {
                try {
                    conn.disconnect();
                } catch (Exception e) {
                }
            }
        }

        JSONObject mm回参  = JSONObject.parseObject(buf.toString());  // 转为json对象
        System.out.println("短信:"+mm回参);
        int mm编码  = mm回参.getIntValue("code");

        if(mm编码==1){
            return  BooleanMessage.getSuccessMessage("发送成功！");
        }else{
            return  BooleanMessage.getErrorMessage(mm回参.getString("message"));
        }
    }

//    public Boolean saveCaptcha(String captcha, String phone) {
//        try {
//            //将验证码存储在redis中，并且设置过期时间5分钟
//            redisTemplate.boundValueOps(phone).set(captcha, 300, TimeUnit.SECONDS);
//            return true;
//        } catch (Exception ex) {
//            throw new RuntimeException(ex);
//        }
//    }
//
//    //验证短信验证码
//    public Boolean checkCaptcha(String captcha, String phone) {
//        try {
//            if (captcha.equals(redisTemplate.boundValueOps(phone).get())) {
//                return true;
//            } else {
//                return false;
//            }
//
//        } catch (Exception ex) {
//            throw new RuntimeException(ex);
//        }
//    }
}

